<?php

namespace App\Models\Home;

use Illuminate\Database\Eloquent\Model;

class FinanceSchedule extends Model
{
    //
    protected $table = 'finance_schedule';
    protected $guarded = [];

    public function finance(){

        return $this->belongsTo('App\Models\Home\Finance','finance_id','id');

    }
    public function getOrderReceipts($between=null,$opt=array()){
        if (is_null($between) || empty($between)){
            $startOfMonth = Carbon::now()->startOfMonth();
            $endOfMonth = Carbon::now()->endOfMonth();
            $between = [$startOfMonth,$endOfMonth];
        }

        $query = self::whereBetween('time', $between)->with(['finance.assign_user.frame.belong_user']);


        if (!empty($opt)){
            foreach ($opt as $k => $v){
                if(is_array($v) && $v[1]){
                    $query = $query->where($k,$v[0],$v[1]);
                }elseif(!is_array($v) && $v !== false){
                    $query = $query->where($k,$v);
                }
            }
        }

        $list = $query->get();


        $data = [];
        foreach ($list as $key => $val){
            $assign = $val->finance->assign;
            if (!isset($data[$assign])){
                $data[$assign]['receipts_1'] = 0;
                $data[$assign]['receipts_0'] = 0;
                $data[$assign]['user_name'] = $val->finance->assign_user?$val->finance->assign_user->username:'';
                $data[$assign]['team_name'] = $val->finance->assign_user?$val->finance->assign_user->frame?$val->finance->assign_user->frame->belong_user?$val->finance->assign_user->frame->belong_user->username:'-':'-':'-';
            }
            if ($val->type == 1){
                $data[$assign]['receipts_1'] += intval($val->receipts);
                }else{
                $data[$assign]['receipts_0'] += intval($val->receipts);
            }
        }

        foreach ($data as $k => $v){
            $data[$k]['profit'] = intval($v['receipts_1']-$v['receipts_0']);
        }

        array_multisort(array_column($data,'profit'),SORT_DESC,$data);

        return $data;

    }


}
